package pl.edu.agh.experts.diseases.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import org.drools.command.GetDefaultValue;
import org.drools.runtime.StatefulKnowledgeSession;

import pl.edu.agh.experts.diseases.DiseaseHolder;
import pl.edu.agh.experts.diseases.Printer;
import pl.edu.agh.experts.diseases.Question;
import pl.edu.agh.experts.diseases.UserResponse;
import pl.edu.agh.experts.diseases.commons.Decision;

public class MainWindowListener implements ActionListener {

	private final MainWindow mainWindow;

	public MainWindowListener(MainWindow mainWindow) {
		this.mainWindow = mainWindow;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		UserResponse userResponse = new UserResponse();
		Boolean yes = true;
		Boolean no = true;
		Boolean dontKnow = true;
		if (mainWindow.getQuestionType() == QuestionType.MetaQuestion) {
			dontKnow = false;
		}
		String answer = "y";
		if (mainWindow.getComboBox().getSelectedItem().equals("Nie")) {
			answer = "n";
		} else if (mainWindow.getComboBox().getSelectedItem().equals("Nie wiem")) {
			answer = "d " + mainWindow.getTextField().getText();
		}

		StatefulKnowledgeSession ksession = mainWindow.getKbaseResults().newStatefulKnowledgeSession();
		ksession.insert(yes);
		ksession.insert(no);
		ksession.insert(dontKnow);
		ksession.insert(answer);
		ksession.insert(userResponse);
		ksession.fireAllRules();

		if (userResponse.getDecision() != null) {
			{
				if (userResponse.getDecision() == Decision.Yes)
					System.out.println("Tak");
				else if (userResponse.getDecision() == Decision.No)
					System.out.println("Nie");
				else if (userResponse.getDecision() == Decision.Maybe)
					System.out.println("Nie wiem ("+userResponse.getWeight()+")");
				
			}
			if (mainWindow.getQuestionType() == QuestionType.MetaQuestion) {
				mainWindow.getQuestionProvider().respondToMetaQuestion(mainWindow.getMetaKnowledge(), userResponse);
			} else if (mainWindow.getQuestionType() == QuestionType.SymptomQuestion) {
				mainWindow.getQuestionProvider().respondToQuestion(new Question(mainWindow.getSymptom(), userResponse),
						mainWindow.getSymptom());
			}
			mainWindow.getTextArea().setText(Printer.getResults(DiseaseHolder.getInstance().getAllDiseases()));
			if (!mainWindow.getQuestionProvider().askPatient()) {
				mainWindow.endOfQuestions();
			}
		}

	}

}
